<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <globalSearchTemplate :config="globalConfig" v-model="listQuery.name" placeholder="请输入姓名"
                            prop="name"></globalSearchTemplate>
      <globalSearchTemplate :config="globalConfig" v-model="listQuery.comeStatus" placeholder="请选择签到状态"
                            prop="comeStatus"
                            type="select"></globalSearchTemplate>
      <globalSearchTemplate :config="globalConfig" v-model="listQuery.backStatus" placeholder="请选择签退状态"
                            prop="backStatus" type="select"></globalSearchTemplate>
      <globalSearchTemplate :config="globalConfig" v-model="listQuery.startTime" type="date"
                            placeholder="开始时间"></globalSearchTemplate>
      <globalSearchTemplate :config="globalConfig" v-model="listQuery.endTime" type="date"
                            placeholder="结束时间"></globalSearchTemplate>
      <el-button class="filter-item" v-waves @click="handleSearch" icon="el-icon-search">搜索</el-button>
      <el-button class="filter-item" v-if="attendanceManager_btn_add" v-waves @click="handleCreate" type="primary"
                 icon="edit">添加
      </el-button>
      <!--      <el-button class="filter-item" v-if="attendanceManager_btn_import" v-waves @click="handleCreate" type="primary"-->
      <!--                 icon="edit">导入-->
      <!--      </el-button>-->
      <el-button class="filter-item" v-if="attendanceManager_btn_export" v-waves @click="submitExport" type="primary"
                 icon="edit">导出
      </el-button>
      <el-upload
        v-if="attendanceManager_btn_import"
        class="upload-demo"
        ref="upload"
        :headers="getHeaders()"
        :action="uploadExcelUrl"
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
        :on-success="uploadSuccess"
        :auto-upload = 'false' >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
      </el-upload>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit
              highlight-current-row style="width: 100%">
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="编号" prop="serialNumber" width="170"></globalTableColumn>
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="姓名" prop="name" width="120"></globalTableColumn>
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="部门" prop="department" width="120"></globalTableColumn>

      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="签到时间" prop="signInTime" width="120"></globalTableColumn>
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="签到状态" prop="comeStatus" type="select" width="120"></globalTableColumn>
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="签退时间" prop="signOutTime" width="120"></globalTableColumn>
      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="签退状态" prop="backStatus" type="select" width="120"></globalTableColumn>

      <globalTableColumn :data="list" :loading.sync="listLoading" :key="key" :config="globalConfig" align="center"
                         label="考勤日期" prop="attendanceDate" width="120"></globalTableColumn>

      <el-table-column label="操作" width="170">
        <template slot-scope="scope">
          <el-button v-if="attendanceManager_btn_upd" size="small" type="success"
                     @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="attendanceManager_btn_del" size="mini" type="danger"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="35%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <globalFormItem :key="formKey" :config="globalConfig" label="姓名" v-model="form.name" prop="name"
                        placeholder="请输入姓名"></globalFormItem>
        <globalFormItem :key="formKey" :config="globalConfig" label="部门" v-model="form.department" prop="department"
                        placeholder="请输入部门"></globalFormItem>
        <el-form-item label="考勤日期">
          <el-date-picker
            v-model="form.attendanceDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请输入考勤日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签到时间">
          <el-time-picker
            v-model="form.signInTime"
            value-format="HH:mm:ss"
            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"
            placeholder="请选择签到时间">
          </el-time-picker>
        </el-form-item>
        <globalFormItem :key="formKey" :config="globalConfig" label="签到状态" v-model="form.comeStatus" prop="comeStatus"
                        placeholder="请输入签到状态" type="select"></globalFormItem>
        <el-form-item label="签退时间">
          <el-time-picker
            v-model="form.signOutTime"
            value-format="HH:mm:ss"
            :picker-options="{selectableRange: '00:00:00 - 23:59:59'}"
            placeholder="请输入签退时间">
          </el-time-picker>
        </el-form-item>
        <globalFormItem :key="formKey" :config="globalConfig" label="签退状态" v-model="form.backStatus"
                        prop="backStatus" placeholder="请输入签退状态" type="select"></globalFormItem>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .filter-item {
    margin-left: 10px;
  }
</style>

<script>
  import { fetchList, getObj, addObj, putObj, delObj, casObj, remoteData,uploadExcel,exportObj } from '@/api/supplier/attendance'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  import { mapGetters } from 'vuex'
  import { globalNotify } from '@/util/notifyUtils'  //弹窗
  import { getToken } from '@/util/auth'
  import globalSearchTemplate from '@/components/global-el-search-template'
  import globalTableColumn from '@/components/global-el-table-column'
  import globalFormItem from '@/components/global-el-form-item'

  export default {
    name: 'attendance',
    components: { globalSearchTemplate, globalTableColumn, globalFormItem },
    directives: {
      waves
    },
    data() {
      return {
        globalConfig: {
          module: ['supplier'],
          componentName: ['attendance']
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          'startTime': undefined,
          'endTime': undefined,
          'name': undefined,
          'attendanceDate': undefined,
          'comeStatus': undefined,
          'backStatus': undefined,
          'signInTime': undefined,
          'signOutTime': undefined,
          'department': undefined
        },
        rules: {},
        form: {
          'name': undefined,
          'attendanceDate': undefined,
          'comeStatus': undefined,
          'backStatus': undefined,
          'signInTime': undefined,
          'signOutTime': undefined,
          'department': undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        attendanceManager_btn_add: false,
        attendanceManager_btn_upd: false,
        attendanceManager_btn_del: false,
        attendanceManager_btn_import: false,
        attendanceManager_btn_export: false,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0,
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        casDataUrl: casObj,
        remoteDataUrl: remoteData,
        key: '',
        formKey: '',
        uploadExcelUrl:uploadExcel
      }
    },
    computed: {
      ...mapGetters([
        'permissions'
      ])
    },
    filters: {},
    created() {
      this.getList()
      this.attendanceManager_btn_add = this.permissions['attendanceManager_btn_add']
      this.attendanceManager_btn_upd = this.permissions['attendanceManager_btn_upd']
      this.attendanceManager_btn_del = this.permissions['attendanceManager_btn_del']
      this.attendanceManager_btn_import = this.permissions['attendanceManager_btn_import']
      this.attendanceManager_btn_export = this.permissions['attendanceManager_btn_export']
    },
    methods: {
      getHeaders() {
        var headers = {
          Authorization: 'Bearer ' + getToken()
        }
        return headers
      },
      submitExport() {
        exportObj(this.listQuery)
      },
      submitUpload() {
        this.$refs.upload.submit()
      },

      beforeAvatarUpload(file) {

        let suffix = file.name.split('.')

        if (suffix[1] === 'xls' || suffix[1] === 'xlsx') {
          return file
        } else {
          this.$message.error('上传文件只能是 xls/xlsx 格式!')
          return false
        }
      },
      uploadSuccess(response) {
        globalNotify(this,response)
        this.$refs.upload.clearFiles()
        this.getList()
      },
      handleRemove(file, fileList) {
      },
      handlePreview(file) {
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
            this.list = response.data.data.records
            this.refreshTable()
            this.total = response.data.data.total
            this.listLoading = false
          }
        )
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDelete(row) {
        delObj(row.id)
          .then(response => {
              this.dialogFormVisible = false
              this.getList()
              globalNotify(this, response)
            }
          )
      },
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.resetForm()
        this.refreshForm()
      },
      refreshTable() {
        this.key = new Date().getTime()
      },
      refreshForm() {
        this.formKey = new Date().getTime()
      },
      handleUpdate(row) {
        this.resetForm()
        getObj(row.id).then(response => {
          this.form = response.data.data
          this.refreshForm()
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })

      },
      create(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
            if (valid) {
              addObj(this.form)
                .then((response) => {
                    this.dialogFormVisible = false
                    this.getList()
                    globalNotify(this, response)
                  }
                )
            } else {
              return false
            }
          }
        )
      },
      cancel(formName) {
        this.resetForm()
        this.dialogFormVisible = false
      },
      update(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
            if (valid) {
              this.dialogFormVisible = false
              this.form.password = undefined
              putObj(this.form).then((response) => {
                  this.dialogFormVisible = false
                  this.getList()
                  globalNotify(this, response)
                }
              )
            } else {
              return false
            }
          }
        )
      },
      resetForm() {
        this.form = {
          'name': undefined,
          'attendanceDate': undefined,
          'comeStatus': undefined,
          'backStatus': undefined,
          'signInTime': undefined,
          'signOutTime': undefined,
          'department': undefined
        }
      },
      handleSearch() {
        this.listQuery.page = 1
        this.getList()
      }
    }
  }
</script>
